import QtQuick 2.0
import QtQuick.Dialogs 1.2
import QtQuick.Window 2.12
import QtQuick.Layouts 1.3
import QtQuick.Controls 2.5
import QtQuick.Dialogs 1.3
import "../components"

Item {



    id: pageProgram



    Connections{
        target: mainwindow
        onTabProgram: {
//            console.log("切换至扩增程序", programName)
            gProgramName_tab = programName
            if(programName === -1){
                curPage = 0
                gProgramList = CAmplProgram.getProgramInfo("0")
                pageList.refreshModelList(gProgramList)
            }
            else{
                gProgramList = CAmplProgram.getProgramInfo("0")
                pageList.refreshModelList(gProgramList)
                for(let i = 0; i < gProgramList.length; i ++){
                    console.log("遍历" + i)
                    if(gProgramList[i]["ProgramName"] === programName){
                        tabDetailPage(i)
                        break
                    }
                }
            }
        }
        onAskForTab:{
            if(mainwindow.mainPage !== 4) return
            if(gProgramName_tab !== -1){
                if(mainwindow.targetPage === 1){
                    mainwindow.mainPage = 1
                    curPage = 0
                }else{
                    boxerror_tab.show()
                }
            }else if(curPage!==1){
                curPage = 0
                mainwindow.permitTab()
            }else{
                if(mainwindow.targetPage !== 4){
                    boxwarining_tabPage.show()
                }
            }

        }
    }

    // 弹窗 ============================================================================
    BoxError{
        id: boxerror_save
    }
    BoxError{
        id: boxerror_tab
        box_text: "请先完成新建实验"
    }

    BoxWarning{
        id: boxwarining_tabPage
        box_text: "当前页面有未保存数据，确认切换页面吗？"
        onAccept: {
            mainwindow.permitTab()
            curPage = 0
        }
    }

    BoxWarning{     // 删除
        id: boxwarining_deleteAll
        onAccept: {
            var res = CAmplProgram.deleteAllProgramInfo();
            gProgramList = CAmplProgram.getProgramInfo("0")
            pageList.refreshModelList(gProgramList)
        }
    }
    BoxWarning{
        id: boxwarning_delete
        box_text: "确认删除吗？"
        onAccept: {
            var res = CAmplProgram.deleteProgramInfo(tempData)
            gProgramList = CAmplProgram.getProgramInfo("0")
            pageList.refreshModelList(gProgramList)
        }
    }



    // 变量 ===========================================================================
    property int curPage: 0   // 0：扩增程序列表  1：新建  2：查看
    property var gProgramName_tab: -1       // 用于界面切换

    property var gProgramList: []
    property var gProgramInfo: []        // 程序信息
    property var gProgramStep: []


    property var originId: ""

    function tabNewPage(){           // 切换至扩增程序详情界面 - 没有id新建

        // 扩增程序数量超出上限
        if(gProgramList.length >= 100){
            mainwindow.showToast("最多创建100条扩增程序", 1)
            return
        }

        // 计算程序编号
        var existMap = {}
        var maxJ = 0
        for(let i = 0; i < gProgramList.length; i ++){
            existMap[gProgramList[i]["Id"].toString()] = 1
            maxJ = Math.max(Number(gProgramList[i]["Id"]), maxJ)
        }
        let j = 1
        for(; j < 100; j ++){
            if( ! existMap.hasOwnProperty(j.toString())){
                break
            }
        }
        if(maxJ < 999) {
            j = maxJ + 1
        }

        originId = ""
        gProgramInfo = {}
        gProgramInfo["Id"] = j;
        gProgramInfo["IsDefault"] = false
        gProgramInfo["ProgramName"] = "程序" + j.toString()
        gProgramInfo["Duration"] = "100"
        gProgramInfo["StepNum"] = 0
        gProgramInfo["HotCoverStatus"] = true
        gProgramInfo["HotCoverTemp"] = 0
        gProgramInfo["CreateDate"] = Qt.formatDateTime(new Date(), "yyyy-MM-dd")
        gProgramInfo["Memo"] = ""
        gProgramInfo["IsTemporary"] = false
        gProgramStep = [{"StepNum": 1,
                         "Temperature": 50,
                         "ExecutionTime": 10,
                         "CycleNumber": 0,
                         "CycleNum": 1,
                         "Id": "abc"+Math.random().toString(),
                         "Rate": 4,
                         "IsCollect": "否"}]
        pageDetails.setProgramInfo(gProgramInfo)
        pageDetails.setProgramStep(gProgramStep)
        curPage = 1
    }
    function tabDetailPage(serial){           // 切换至扩增程序详情界面 - 有id调用后端

        originId = gProgramList[serial]["Id"]
        gProgramInfo = gProgramList[serial]
        gProgramStep = CAmplProgram.getProgramStepInfo(gProgramList[serial]["Id"], "0")

        pageDetails.setProgramInfo(gProgramInfo)
        pageDetails.setProgramStep(gProgramStep)
        curPage = 2
    }

    function tabListPage(){             // 切换至扩增程序列表界面
        gProgramList = CAmplProgram.getProgramInfo("0")
        curPage = 0
        pageList.refreshModelList(gProgramList)
    }

    function deleteAll(){               // 全部删除
        boxwarining_deleteAll.setText("确认全部删除吗")
        boxwarining_deleteAll.show()
    }

    function saveProgram(){              // 保存

        if(gProgramInfo["Id"] === "" || gProgramInfo["ProgramName"] === ""){
            boxerror_save.setText("请填写程序Id和程序名称")
            boxerror_save.show()
            return
        }
        if(gProgramInfo["Id"] === "0" || gProgramInfo["Id"] === "00" || gProgramInfo["Id"] === "000"){
            boxerror_save.setText("扩增程序Id不能为0")
            boxerror_save.show()
            return
        }

        var res = CAmplProgram.checkedProgramInfo(gProgramInfo, gProgramStep);
        if(res === "校验成功"){
            if(originId != ""){
                console.log("删除id:" + originId)
                CAmplProgram.deleteProgramInfo(originId)
            }
            CAmplProgram.saveProgramInfo(gProgramInfo, gProgramStep);
            if(curPage === 1){
                mainwindow.showToast("创建成功", 0)
                pageProgram.tabListPage()
                gProgramList = CAmplProgram.getProgramInfo("0")
                pageList.refreshModelList(gProgramList)
            }else if(curPage === 2){
                mainwindow.showToast("保存成功", 0)
                pageProgram.tabListPage()
                gProgramList = CAmplProgram.getProgramInfo("0")
                pageList.refreshModelList(gProgramList)
            }

        }else{
            boxerror_save.setText(res)
            boxerror_save.show()
        }

    }

    function deleteProgram(id){           // 删除
        boxwarning_delete.tempData = id
        boxwarning_delete.show()
    }

    function setDefault(id, val){
        var res = CAmplProgram.setDefaultProgram(id, val);
        gProgramList = CAmplProgram.getProgramInfo("0")
        pageList.refreshModelList(gProgramList)
    }


    anchors.fill: parent
    anchors.margins: 15


    // 表头
    Rectangle{                  // 扩增程序列表 =======================================================
        color: "transparent"
        visible: curPage === 0
        height: 40*dp
        width: parent.width
        Rectangle{
            x:0
            width: 100*dp
            anchors.verticalCenter: parent.verticalCenter
            Text {
                text: qsTr("程序")
                font.bold: true
                font.pixelSize: config.fontsize + 4
                anchors.verticalCenter: parent.verticalCenter
            }
        }
        PushButton{
            id: button_new
            x: parent.width - 260*dp
            title: "全部删除"
            anchors.verticalCenter: parent.verticalCenter
            defaultMode2: true
            onReleased: {
                pageProgram.deleteAll()
            }
        }
        PushButton{
            id: button_deleteAll
            x: parent.width - 120*dp
            anchors.verticalCenter: parent.verticalCenter
            defaultMode1: true
            title: "新建程序"
            onReleased: {
                pageProgram.tabNewPage()
            }
        }
    }

    Rectangle{                  // 新建程序 ==============================================
        height: 40*dp
        width: parent.width
        color: "transparent"
        visible: curPage !== 0
        Rectangle{
            x: 0
            width: 100*dp
            anchors.verticalCenter: parent.verticalCenter
            color: "transparent"
            Text {
                id: name
                text: curPage===1 ? "新建程序" : "查看程序"
                font.bold: true
                font.pixelSize: config.fontsize + 4
                anchors.verticalCenter: parent.verticalCenter
            }
        }
        PushButton{
            id:button_cancel
            x: parent.width-260*dp
            anchors.verticalCenter: parent.verticalCenter
            defaultMode2: true
            title: "取消"
            onReleased: {
                if(gProgramName_tab === -1){
                    pageProgram.tabListPage()
                }else{
                    mainwindow.tabExperiment()
                    mainwindow.mainPage = 1
                }
            }
        }
        PushButton{
            id: button_save
            title: "保存"
            x: parent.width-120*dp
            anchors.verticalCenter: parent.verticalCenter
            defaultMode1: true
            onReleased: {

                // 同步程序信息
                pageDetails.syncInfo()
                pageDetails.syncItem()
                pageProgram.saveProgram()
            }
        }
    }


    Rectangle{

        y: 50*dp
        width: parent.width
        height: parent.height - 50*dp

        color: "transparent"
        ProgramList{
            id: pageList
            anchors.fill: parent
            visible: curPage === 0
        }

        ProgramDetails{
            id: pageDetails
            anchors.fill: parent
            visible: curPage !== 0
            editable: curPage===1 ? 1 : 2
        }
    }

}
